﻿using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using WoodAdmin.Common.Extention;
using WoodAdmin.Common.Helper;
using WoodAdmin.Models;
using WoodAdmin.Models.ViewModels;
using WoodAdmin.Services;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using X.PagedList;

namespace WoodAdmin.Controllers
{
    public class SysUserController : BaseController
    {
        private readonly SysUserService _service;
        private readonly SysRoleService _roleService;
        private readonly SysUserRoleService _userRoleService;
        private ISession _session => HttpContext.Session;
        public SysUserController(SysUserService service, SysRoleService roleService, SysUserRoleService userRoleService)
        {
            _service = service;
            _roleService = roleService;
            _userRoleService = userRoleService;
        }

        #region 列表
        /// <summary>
        /// 列表
        /// </summary>
        /// <returns></returns>
        public IActionResult Index(SysUser model,int page=1)
        {
            ViewBag.SearchModel = model;
            var list = _service.Queryable();
            if (!string.IsNullOrEmpty(model.Name))
            {
                list = list.Where(a => 
                    SqlFunc.Contains(a.Name, model.Name) ||
                    SqlFunc.Contains(a.NickName, model.Name)
                    ).ToList();
            }
            var pageList = list.ToPagedList(page, 15);
            return View(pageList);
        }
        #endregion

        #region 编辑
        /// <summary>
        /// 编辑/添加
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet]
        public IActionResult AddEdit(int id)
        {
            SysUser model = _service.FindEntity(id);
            if (model==null)
            {
                model = new SysUser();
            }
            else
            {
                model.RoleIds = _userRoleService.Queryable(p=>p.UserID==id).Select(p=>p.RoleID).ToList();
            }
            return View(model);
        }

        /// <summary>
        /// 编辑/添加
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost]
        public IActionResult AddEdit(SysUser model)
        {
            using (var db = DbContext.Db)
            {
                var rs = db.Ado.UseTran(() => {
                    if (model.ID > 0)
                    {
                        #region 设置用户权限

                        //用户角色设置
                        //批量删除旧的
                        var oldIds = db.Queryable<SysUserRole>().Where(a => a.UserID == model.ID).Select(p => p.UserID);
                        db.Deleteable<SysUserRole>().In(a => a.UserID, oldIds).ExecuteCommand();

                        //批量增加新的
                        List<SysUserRole> list = new List<SysUserRole>();
                        if (model.RoleIds.Count > 0)
                        {
                            foreach (var roleid in model.RoleIds)
                            {
                                list.Add(new SysUserRole { UserID = model.ID, RoleID = roleid, CreateMan = 1, CreateTime = DateTime.Now });
                            }
                        }
                        db.Insertable(list).ExecuteCommand();

                        #endregion 设置用户权限

                        //用户密码修改
                        var oldPass = db.Queryable<SysUser>().First()?.Password;
                        var newPass = model.Password;
                        if (oldPass != newPass)
                        {
                            model.Password = newPass.ToMD5String();
                        }
                        else
                        {
                            model.Password = oldPass;
                        }
                        //用户信息修改
                        var res = db.Updateable(model).IgnoreColumns(ignoreAllNullColumns: true).ExecuteCommand();
                        if (res > 0)
                        {
                            return JsonSuccess();
                        }
                    }
                    else
                    {
                        model.Password = model.Password.ToMD5String();
                        model.CreateTime = DateTime.Now;
                        var userid = db.Insertable(model).ExecuteReturnEntity().ID;
                        if (userid > 0)
                        {
                            //批量增加新的
                            List<SysUserRole> list = new List<SysUserRole>();
                            if (model.RoleIds.Count > 0)
                            {
                                foreach (var roleid in model.RoleIds)
                                {
                                    list.Add(new SysUserRole { UserID = userid, RoleID = roleid, CreateMan = 1, CreateTime = DateTime.Now });
                                }
                            }
                            if (db.Insertable(list).ExecuteCommand() > 0)
                            {
                                return JsonSuccess();
                            }
                        }
                    }
                    return JsonError();
                });

                return rs.Data;
            }
        }
        #endregion

        #region 删除
        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public IActionResult Delete(int id)
        {
            if (_service.Delete(id))
            {
                return JsonSuccess("删除成功！");
            }
            return JsonError("删除失败");
        }
        #endregion

        #region 修改密码
        /// <summary>
        /// 修改密码
        /// </summary>
        /// <returns></returns>
        public IActionResult UpdatePassword()
        {
            return View();
        }

        /// <summary>
        /// 修改密码
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public IActionResult UpdatePassword(UpdatePasswordModel model)
        {
            //RSA解密前台传入的密码
            var rsa = new RSAHelper(RSAType.RSA, Encoding.UTF8, APPKeys.PrivateKey, APPKeys.PublicKey);
            model.OldPass = rsa.Decrypt(model.OldPass);
            model.NewPass = rsa.Decrypt(model.NewPass);
            model.ConfirmPass = rsa.Decrypt(model.ConfirmPass);

            var curUser = CurrentUser;
            if (!model.OldPass.ToMD5String().Equals(curUser.Password))
            {
                return JsonError("原密码不正确！");
            }
            if (!model.NewPass.Equals(model.ConfirmPass))
            {
                return JsonError("两次密码输入不一致！");
            }
            curUser.Password = model.NewPass.ToMD5String();
            curUser.ModifyTime = DateTime.Now;
            curUser.ModifyMan = 1;
            if (_service.Update(curUser))
            {
                return JsonSuccess(APPKeys.Success);
            }
            return JsonSuccess(APPKeys.Failed);
        }
        #endregion

        #region 登出
        /// <summary>
        /// 注销
        /// </summary>
        public IActionResult Logout()
        {
            //清空缓存
            _session.Remove(APPKeys.CurrentUser);
            _session.Remove(APPKeys.CurrentUserAuthNode);
            _session.Remove(APPKeys.CurrentUserRoles);
            return Redirect("/Login/Login");
        }
        #endregion
    }
}